#include "stdafx.h"
#include "SpectatorController.h"
#include "InputManager.h"
#include "Windows.h"

SpectatorController::SpectatorController (Model *model, Ogre::RenderWindow* window, Ogre::Camera* camera) {
  setModel(model);
	player = NULL;
	m_cObject = new CameraObject();
	m_camera = camera;
	m_currentModel->addGameObject(m_cObject, m_currentModel->getNextID(), 0,0,0);
	m_currentModel->attachCamera(m_cObject, m_camera);
	InputManager::getInstance()->registerObserver(this);
}

SpectatorController::~SpectatorController () {
	delete m_cObject;
}

bool SpectatorController::update(float deltaTime) {
  //TODO make OgreApplication windowlistener too
	
	OIS::Keyboard* keyboard = InputManager::getInstance()->getKeyboard();
	if(keyboard->isKeyDown(OIS::KC_ESCAPE)) {
  		return false;
	}
	
	if(m_cObject) {
		if(keyboard->isKeyDown(OIS::KC_W)) {
			m_cObject->move(0,0,1);
		}
		if(keyboard->isKeyDown(OIS::KC_A)) {
			m_cObject->move(1,0,0);
		}
		if(keyboard->isKeyDown(OIS::KC_S)) {
			m_cObject->move(0,0,-1);
		}
		if(keyboard->isKeyDown(OIS::KC_D)) {
			m_cObject->move(-1,0,0);
		} 	
	}
	
  return true;
}

bool SpectatorController::keyPressed(const OIS::KeyEvent &arg) {
	if (arg.key == OIS::KC_L && player != NULL) {
		m_currentModel->attachCamera(player->getAvatarController()->getPlayerAvatar());
		player->playerSpawn();
	}
	return true;
}

bool SpectatorController::keyReleased(const OIS::KeyEvent &arg) {
	return true;
}
	
bool SpectatorController::mouseMoved( const OIS::MouseEvent &arg ) {
	m_cObject->cameraLookAround(-arg.state.X.rel, arg.state.Y.rel);
	return true;
}

bool SpectatorController::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) {
	if(id == OIS::MB_Left) {
		m_currentModel->attachCamera(m_currentModel->getNextPlayerAvatar());
	}
	
	if (id == OIS::MB_Right) {
		m_cObject->setPosition(m_currentModel->getCameraPosition());
		//m_cObject->getCameraNode()->setOrientation(m_currentModel->getCameraOrientation());
		m_currentModel->attachCamera(m_cObject);
	}
	return true;
}

void SpectatorController::setActive(bool in) {
	m_active = in;
	inputActive = in;
}

void SpectatorController::setPlayer(Player* p) {
	player = p;
}
